package com.store.app.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.Result;
import com.store.app.ExitApplication;
import com.store.app.LocationApplication;
import com.store.app.MainActivity;
import com.store.app.R;
import com.store.app.bean.CouponUpdateBean;
import com.store.app.imlife.utils.ToastTools;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.UserTokenUtils;
import com.store.app.zxing.Capture_ZxingActivity;

import net.sourceforge.zbar.ImageScanner;

import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;

import de.greenrobot.event.EventBus;

//核销优惠券页面
public class ValidateCouponActivity extends Capture_ZxingActivity implements IOnHttpListener, OnClickListener {

    private static String cardNo;//卡号
    private RelativeLayout ryScanResult;
    private TextView tvCardCode;
    private TextView tvCardStatus;
    private static final int MSG_REQUEST_SUCCESS = 0;
    private static final int MSG_REQUEST_FAILED = 1;
    private static final int MSG_QUERY_FAMILY_CARD_SUCCESS = 2;//成功
    private static final int MSG_QUERY_FAMILY_CARD_FAIL = 3;//失败（亲情卡已激活）
    private static final int MSG_RESTART_SCAN = 4;//重新开启扫描
    private Handler mHandler;
    private ImageScanner mImageScanner = null;
    private TextView tv_cap;
    private String cardState;
    private String cardStateInfo;
    private NetRequest netRequest;
    private RelativeLayout rl_dialog_fail;      //失败弹窗
    private RelativeLayout rl_dialog_success;   //成功弹窗
    private TextView tv_fail_ok;
    private TextView tv_success_ok;
    private TextView tv_dialog_success_content;
    private String sktCode;
    private Dialog dialog;
    private TextView tv_fail_content;

    @Override
    public void onAfinalFail() {
        rl_dialog_success.setVisibility(View.GONE);
        rl_dialog_fail.setVisibility(View.GONE);
        showToast("请检查本地网络！");
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        if (requestId == 1) {
            EventBus.getDefault().post(new CouponUpdateBean(2));
            tv_dialog_success_content.setText("核销成功");
            rl_dialog_success.setVisibility(View.VISIBLE);
        } else if (requestId == 2) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
                dialogBuilder.create();
                LayoutInflater inflater = LayoutInflater.from(this);
                View temp = inflater.inflate(R.layout.dialog_youhuiquan, null);
                TextView tv_ok = (TextView) temp.findViewById(R.id.tv_ok);
                TextView tv_cancel = (TextView) temp.findViewById(R.id.tv_cancel);
                tv_ok.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!TextUtils.isEmpty(MainActivity.member_id) && !TextUtils.isEmpty(sktCode)) {
                            dialog.dismiss();
                            //如果是这种状态 说明验证过了
                            netRequest.requestCouponValidate(1, sktCode);
                        }
                    }
                });
                tv_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                    }
                });
                dialogBuilder.setView(temp);
                dialog = dialogBuilder.show();
            } catch (Exception e) {

            }
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        ToastTools.showShort(ValidateCouponActivity.this, msg);
    }

    private void initView() {
        rl_dialog_fail = (RelativeLayout) findViewById(R.id.rl_dialog_fail);
        rl_dialog_success = (RelativeLayout) findViewById(R.id.rl_dialog_success);
        tv_fail_ok = (TextView) findViewById(R.id.tv_fail_ok);
        tv_fail_content = (TextView) findViewById(R.id.tv_fail_content);
        tv_fail_ok.setOnClickListener(this);
        tv_success_ok = (TextView) findViewById(R.id.tv_success_ok);
        tv_success_ok.setOnClickListener(this);
        tv_dialog_success_content = (TextView) findViewById(R.id.tv_dialog_success_content);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_fail_ok:
                rl_dialog_fail.setVisibility(View.GONE);
                break;
            case R.id.tv_success_ok:
                rl_dialog_success.setVisibility(View.GONE);
                break;
        }
    }

    private class WeakHandler extends Handler {
        private final WeakReference<ValidateCouponActivity> mReference;

        public WeakHandler(ValidateCouponActivity activity) {
            mReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            ValidateCouponActivity activity = mReference.get();
            if (activity == null) {
                return;
            }
            activity.dismissProgressDialog();
            switch (msg.what) {

                case MSG_QUERY_FAMILY_CARD_SUCCESS:
                    break;
                case MSG_QUERY_FAMILY_CARD_FAIL:
//					Toast.makeText(ValidateCouponActivity.this,cardStateInfo,Toast.LENGTH_LONG).show();
                    break;
                case MSG_RESTART_SCAN:
                    Log.v("zyl", "重新开启扫描");
                    setReCapture();
                    break;
                default:
                    break;
            }
        }
    }


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_validate_coupon);
        initView();
        getWindow()
                .addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setInintView();
        initData();
        mHandler = new WeakHandler(this);
        findViewById();
    }

    private void initData() {
        UserTokenUtils.setUerToken(this);
        netRequest = new NetRequest(this);
    }

    private void findViewById() {
        findViewById(R.id.retreat).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tv_cap = (TextView) findViewById(R.id.cap_tv);
        int width = LocationApplication.app.getDM().widthPixels;
        int high = LocationApplication.app.getDM().heightPixels;
        width = width / 8 * 3;
        high = high / 2 + width;
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.topMargin = high + MainActivity.dip2px(20);
        layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
        tv_cap.setLayoutParams(layoutParams);
        tv_cap.setText("扫描优惠券二维码,进行快速核销！");
    }


    /**
     * 处理扫描结果
     *
     * @param result
     * @param barcode
     */
    public void handleDecode(Result result, Bitmap barcode) {

        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        String resultString = result.getText();
        Log.v("zyl", "resultString:" + resultString);

        if (resultString.equals("")) {
            Toast.makeText(ValidateCouponActivity.this, "扫描错误!", Toast.LENGTH_SHORT).show();
            mHandler.sendEmptyMessageDelayed(MSG_RESTART_SCAN, 3000);
        } else {
            if (!TextUtils.isEmpty(resultString)) {
                if (resultString.length() > 3) {
                    String identifying = resultString.substring(0, 3);
                    if (identifying.equals("YHQ")) {
                        sktCode = resultString.substring(3, resultString.length());
                        if (!TextUtils.isEmpty(sktCode)) {
//                            netRequest.requestCouponValidate(1, sktCode);
                            netRequest.requestValidateFindForStores(2, sktCode);
                        }
                        else {
                            Toast.makeText(ValidateCouponActivity.this, "此二维码非优惠券！", Toast.LENGTH_SHORT).show();
                        }
                        Log.v("zyl", "YHQ---SKTCODE:" + sktCode);
                        mHandler.sendEmptyMessageDelayed(MSG_RESTART_SCAN, 6000);
                    } else {
                        mHandler.sendEmptyMessageDelayed(MSG_RESTART_SCAN, 3000);
                        Toast.makeText(ValidateCouponActivity.this, "此二维码非优惠券！", Toast.LENGTH_SHORT).show();
                    }
                }
                cardNo = resultString;
            }
        }
    }


    private int getStatusBarHeight() {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
